<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="the-button">操作蓝牙</button>
</body>
<script>
  const button = document.querySelector('#the-button');

  // let options = {
  //   filters: [
  //     { services: ['heart_rate'] },
  //     { services: [0x1802, 0x1803] },
  //     { services: ['c48e6067-5295-48d3-8d5c-0395f61792b1'] },
  //     { name: 'Shenbankeji-BT-200' },
  //     { namePrefix: 'Shen' }
  //   ],
  //   optionalServices: ['battery_service']
  // }
  (async () => {
      try {
        const isBluetoothAvailable = await navigator.bluetooth.getAvailability();
        if(!isBluetoothAvailable){
          window.alert("本设备未检测到蓝牙模块！请使用含有蓝牙的设备进行操作！")
          // window.alert(`> Bluetooth is ${isBluetoothAvailable ? 'available' : 'unavailable'}`);
        }
      } catch (error) {
        window.alert(error);
      }
    })();

    // if ('onavailabilitychanged' in navigator.bluetooth) {
    //   navigator.bluetooth.addEventListener('availabilitychanged', function (event) {
    //     console.log(`> Bluetooth is ${event.value ? 'available' : 'unavailable'}`);
    //   });
    // }

  button.addEventListener('click', function () {
    navigator.bluetooth.requestDevice({ 
      acceptAllDevices: true
     })
      .then(device => {
        console.log(device)
        console.log('> Requested ' + device.name + ' (' + device.id + ')');
      })
      // .then(server => {
      //   console.log('Getting Battery Service...');
      //   return server.getPrimaryService('battery_service');
      // }).then(service => {
      //   console.log('Getting Battery Level Characteristic...');
      //   return service.getCharacteristic('battery_level');
      // }).then(characteristic => {
      //   console.log('Reading Battery Level...');
      //   return characteristic.readValue();
      // }).then(value => {
      //   let batteryLevel = value.getUint8(0);
      //   console.log('> Battery Level is ' + batteryLevel + '%');
      // }).catch(error => {
      //   console.log('Argh! ' + error);
      // });
  })
</script>

</html>